<template>
  <div v-if="show" class="modal-overlay">
    <div class="modal-content">
      <div class="modal-header">
        <h3>更新库存</h3>
        <button class="close-btn" @click="handleClose">×</button>
      </div>
      <div class="modal-body">
        <div class="item-info">
          <p><strong>操作人：</strong>{{ currentUserNickname }}</p>
          <p><strong>操作日期：</strong>{{ currentDate }}</p>
          <p><strong>物品名称：</strong>{{ item.name }}</p>
          <p><strong>库存数量：</strong>{{ item.stockNum }} {{ item.unit }}</p>
        </div>
        <div class="form-group">
          <label for="operationType">操作类型</label>
          <select id="operationType" v-model="operationType" class="form-select">
            <option v-if="isAdmin || isAdvancedLibraryAdmin || isEditRole || isAssignRole" :value="0">入库</option>
            <option v-if="isAdmin || isAdvancedLibraryAdmin || isEditRole || isoutboundRole || isAssignRole" :value="1">出库</option>
          </select>
          <div v-if="!hasAvailableOperations" class="error-message">
            您没有执行任何库存操作的权限
          </div>
        </div>
        <div class="form-group">
          <label for="updateAmount">{{ operationType === 1 ? '出库' : '入库' }}数量</label>
          <div class="input-with-unit">
            <input
              id="updateAmount"
              v-model.number="updateAmount"
              type="number"
              min="0.01"
              placeholder="请输入数量"
              :class="{ 'error': showError && !isValidAmount }"
            />
            <span class="unit-label">{{ item.unit }}</span>
          </div>
          <div class="error-message" v-if="showError && !isValidAmount">
            请输入有效的数量（大于0）
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button class="cancel-btn" @click="handleClose">取消</button>
        <button 
          class="submit-btn" 
          @click="handleSubmit"
          :disabled="isSubmitting"
        >
          {{ isSubmitting ? '提交中...' : '确认' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { API_CONFIG } from '../../config/apiConfig';
import type { InventoryItem } from '../../types/inventory';
import { ToastService } from '../../utils/toastService';
import type { User } from '../../types';
import { useLabStore } from '../../stores/labStore';

// 使用lab store
const store = useLabStore();

// 获取当前登录用户信息
const userInfoStr = localStorage.getItem('userInfo');
const currentUser = ref<User | null>(userInfoStr ? JSON.parse(userInfoStr) : null);
const isAdmin = computed(() => currentUser.value?.roleName === '超级管理员');
const isAdvancedLibraryAdmin = computed(() => {
  if (isAdmin.value) return false;
  if (!currentUser.value?.researchRoleInfos || !store.selectedLab?.id) return false;
  return Object.entries(currentUser.value.researchRoleInfos).some(
    ([groupId, roleId]) => groupId === store.selectedLab?.id && roleId === 4
  );
});
const isEditRole = computed(() => {
  if (isAdmin.value || isAdvancedLibraryAdmin.value) return false;
  if (!currentUser.value?.researchRoleInfos || !store.selectedLab?.id) return false;
  return Object.entries(currentUser.value.researchRoleInfos).some(
    ([groupId, roleId]) => groupId === store.selectedLab?.id && roleId === 10
  );
});
const isoutboundRole = computed(() => {
  if (isAdmin.value || isAdvancedLibraryAdmin.value) return false;
  if (!currentUser.value?.researchRoleInfos || !store.selectedLab?.id) return false;
  return Object.entries(currentUser.value.researchRoleInfos).some(
    ([groupId, roleId]) => groupId === store.selectedLab?.id && roleId === 9
  );
});

const isAssignRole = computed(() => {
  if (isAdmin.value || isAdvancedLibraryAdmin.value) return false;
  if (!currentUser.value?.researchRoleInfos || !store.selectedLab?.id) return false;
  return Object.entries(currentUser.value.researchRoleInfos).some(
    ([groupId, roleId]) => groupId === store.selectedLab?.id && roleId === 12
  );
});

// 定义props
const props = defineProps<{
  show: boolean;
  item: InventoryItem;
}>();

const emit = defineEmits<{
  (e: 'close'): void;
  (e: 'update-success'): void;
}>();

// 获取当前用户昵称
const currentUserNickname = computed(() => {
  const userInfo = localStorage.getItem('userInfo');
  if (userInfo) {
    const { nickname } = JSON.parse(userInfo);
    return nickname || '未知用户';
  }
  return '未知用户';
});

// 获取当前日期（年月日格式）
const currentDate = computed(() => {
  const now = new Date();
  return now.toLocaleDateString('zh-CN'); // 使用中文日期格式 (年/月/日)
});

// 计算属性：检查是否有可用的操作类型
const hasAvailableOperations = computed(() => {
  return (isAdmin.value || isAdvancedLibraryAdmin.value || isEditRole.value || isoutboundRole.value || isAssignRole.value);
});

// 表单数据
const operationType = ref<number>(isAdmin.value || isAdvancedLibraryAdmin.value || isEditRole.value || isAssignRole.value ? 0 : 1); // 根据权限设置默认值
const updateAmount = ref<number | null>(null);
const isSubmitting = ref(false);
const showError = ref(false);

// 验证数量是否有效
const isValidAmount = computed(() => {
  return updateAmount.value !== null && updateAmount.value > 0;
});

// 不再需要从stockNumAndUnit中提取单位部分，直接使用item.unit

// 关闭模态框
const handleClose = () => {
  operationType.value = 1;
  updateAmount.value = null;
  showError.value = false;
  emit('close');
};

// 提交表单
// 监听权限变化，更新操作类型
watch(
  [isAdmin, isAdvancedLibraryAdmin, isEditRole, isoutboundRole, isAssignRole],
  ([newIsAdmin, newIsAdvancedLibraryAdmin, newIsEditRole, newisoutboundRole,newIsAssignRole]) => {
    const canAdd = newIsAdmin || newIsAdvancedLibraryAdmin || newIsEditRole || newIsAssignRole;
    const canOut = canAdd || newisoutboundRole;
    
    if (!canAdd && !canOut) {
      // 如果没有任何权限，保持当前值
      return;
    }
    // 如果当前操作类型对应的权限被移除，切换到有权限的操作类型
    if ((operationType.value === 0 && !canAdd) || 
        (operationType.value === 1 && !canOut)) {
      operationType.value = canAdd ? 0 : 1;
    }
  }
);

const handleSubmit = async () => {
  // 显示验证错误
  showError.value = true;
  
  // 验证表单
  if (!isValidAmount.value) {
    return;
  }
  
  // 验证权限
  if ((operationType.value === 0 && !(isAdmin.value || isAdvancedLibraryAdmin.value || isEditRole.value || isAssignRole.value)) || 
      (operationType.value === 1 && !(isAdmin.value || isAdvancedLibraryAdmin.value || isEditRole.value || isoutboundRole.value || isAssignRole.value))) {
    ToastService.error('您没有执行此操作的权限');
    return;
  }

  isSubmitting.value = true;
  try {
    // 准备请求数据
      const requestData = {
        id: props.item.id,
        operationType: operationType.value,
        num: String(updateAmount.value),
        takenBy: currentUserNickname.value,
        takenDate: currentDate.value,
        researchGroupId: store.selectedLab?.id
      };

    // 发送请求
    const response = await fetch(`${API_CONFIG.BASE_URL}/inventory/sku/${props.item.id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      credentials: 'include',
      body: JSON.stringify(requestData)
    });

    const result = await response.json();
    
    if (result.code === 0 || result.code === '0') {
      emit('update-success');
      handleClose();
    } else {
      ToastService.error(`更新失败: ${result.msg}`);
    }
  } catch (error) {
    console.error('更新库存请求失败:', error);
    ToastService.error('更新库存失败，请检查网络连接');
  } finally {
    isSubmitting.value = false;
  }
};
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 400px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.modal-header {
  padding: 16px 24px;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  color: #999;
  cursor: pointer;
  padding: 4px;
}

.close-btn:hover {
  color: #666;
}

.modal-body {
  padding: 24px;
}

.item-info {
  margin-bottom: 20px;
  padding: 12px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.item-info p {
  margin: 8px 0;
  font-size: 14px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #333;
  font-size: 14px;
}

.form-group input,
.form-select {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s;
}

.form-group input:focus,
.form-select:focus {
  border-color: #40a9ff;
  outline: none;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.form-group input.error {
  border-color: #ff4d4f;
}

.input-with-unit {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
}

.input-with-unit input {
  flex: 1;
  min-width: 0;
}

.unit-label {
  color: #666;
  font-size: 14px;
  white-space: nowrap;
}

.error-message {
  color: #ff4d4f;
  font-size: 12px;
  margin-top: 4px;
}

.modal-footer {
  padding: 16px 24px;
  border-top: 1px solid #e8e8e8;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.cancel-btn,
.submit-btn {
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.cancel-btn {
  background: white;
  border: 1px solid #d9d9d9;
  color: #666;
}

.cancel-btn:hover {
  color: #40a9ff;
  border-color: #40a9ff;
}

.submit-btn {
  background: #1890ff;
  border: none;
  color: white;
}

.submit-btn:hover {
  background: #40a9ff;
}

.submit-btn:disabled {
  background: #d9d9d9;
  cursor: not-allowed;
}
</style>